import { API_URL } from "./constant";
import PollingManager from "./PollingManager";

document.addEventListener("DOMContentLoaded", () => {
  const settingsForm = document.getElementById(
    "settingsForm"
  ) as HTMLFormElement;
  const openKey = document.getElementById("openKey") as HTMLInputElement;
  const passwd = document.getElementById("passwd") as HTMLInputElement;
  const saveSettings = document.getElementById(
    "saveSettings"
  ) as HTMLButtonElement;

  // 设置版本号
  const appTitle = document.getElementById("appTitle") as HTMLHeadingElement;
  if (appTitle) {
    appTitle.textContent = `爆蚁ERP小助手新${chrome.runtime.getManifest().version}`;
  }

  // 初始化检查登录状态
  checkLoginStatus();

  // 打开对话框的方法
  function openIPListDialog(data: any) {
    // 创建对话框背景
    const backdrop = document.createElement("div");
    backdrop.style.cssText = `
      position: fixed;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      background: rgba(0, 0, 0, 0.5);
      display: flex;
      align-items: center;
      justify-content: center;
      z-index: 1000;
      animation: fadeIn 0.3s;
  `;

    // 创建对话框内容
    const dialog = document.createElement("div");
    dialog.style.cssText = `
      background: white;
      width: 100%;
      max-height: 80vh;
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
      display: flex;
      flex-direction: column;
      animation: slideIn 0.3s;
  `;

    // 对话框标题
    const titleBar = document.createElement("div");
    titleBar.style.cssText = `
      border-bottom: 1px solid #eee;
      display: flex;
      justify-content: space-between;
      align-items: center;
      font-weight: bold;
      font-size: 16px;
  `;
    titleBar.textContent = "超出登录设备,请选择替换设备";

    // 关闭按钮
    const closeBtn = document.createElement("button");
    closeBtn.style.cssText = `
      background: none;
      border: none;
      cursor: pointer;
      font-size: 18px;
      color: #666;
  `;
    closeBtn.textContent = "×";
    closeBtn.onclick = () => document.body.removeChild(backdrop);
    titleBar.appendChild(closeBtn);

    // 表格容器
    const tableContainer = document.createElement("div");
    tableContainer.style.cssText = `
      overflow: auto;
      flex: 1;
  `;

    // 创建表格
    const table = document.createElement("table");
    table.style.cssText = `
      width: 100%;
      border-collapse: collapse;
      font-size: 14px;
  `;

    // 表头
    const thead = document.createElement("thead");
    thead.innerHTML = `
      <tr style="background: #f5f5f5;">
          <th style="text-align: left; border-bottom: 1px solid #eee; font-weight: bold;">IP地址</th>
          <th style="text-align: left; border-bottom: 1px solid #eee; font-weight: bold;">登录时间</th>
          <th style="text-align: left; border-bottom: 1px solid #eee; font-weight: bold;">操作</th>
      </tr>
  `;

    // 表体
    const tbody = document.createElement("tbody");

    // 添加数据行
    data.forEach((item: any, index: any) => {
      const tr = document.createElement("tr");
      tr.style.backgroundColor = index % 2 === 0 ? "#fff" : "#fafafa";
      tr.onmouseover = () => (tr.style.backgroundColor = "#f0f0f0");
      tr.onmouseout = () =>
        (tr.style.backgroundColor = index % 2 === 0 ? "#fff" : "#fafafa");

      tr.innerHTML = `
          <td style="border-bottom: 1px solid #eee;">${item.loginIp}</td>
          <td style="border-bottom: 1px solid #eee;">${item.createTime}</td>
          <td style="border-bottom: 1px solid #eee;">
              <button class="replace-btn" data-id="${item.id}" style="
                  margin-right: 8px;
                  background: #0078d7;
                  color: white;
                  border: none;
                  border-radius: 3px;
                  cursor: pointer;
              ">替换</button>
          </td>
      `;

      tbody.appendChild(tr);
    });

    // 如果没有数据
    if (data.length === 0) {
      const tr = document.createElement("tr");
      tr.innerHTML = `
          <td colspan="3" style="padding: 24px; text-align: center; color: #999; border-bottom: 1px solid #eee;">
              暂无数据
          </td>
      `;
      tbody.appendChild(tr);
    }

    // 组装表格
    table.appendChild(thead);
    table.appendChild(tbody);
    tableContainer.appendChild(table);

    // 底部按钮区
    const footer = document.createElement("div");
    footer.style.cssText = `
      border-top: 1px solid #eee;
      display: flex;
      justify-content: flex-end;
  `;

    const cancelBtn = document.createElement("button");
    cancelBtn.textContent = "关闭";
    cancelBtn.style.cssText = `
      background: #f5f5f5;
      border: 1px solid #ddd;
      border-radius: 4px;
      cursor: pointer;
  `;
    cancelBtn.onclick = () => document.body.removeChild(backdrop);
    footer.appendChild(cancelBtn);

    // 组装对话框
    dialog.appendChild(titleBar);
    dialog.appendChild(tableContainer);
    dialog.appendChild(footer);
    backdrop.appendChild(dialog);

    // 添加到页面
    document.body.appendChild(backdrop);

    // 添加动画样式
    const style = document.createElement("style");
    style.textContent = `
      @keyframes fadeIn {
          from { opacity: 0; }
          to { opacity: 1; }
      }
      @keyframes slideIn {
          from { transform: translateY(-20px); opacity: 0; }
          to { transform: translateY(0); opacity: 1; }
      }
  `;
    backdrop.appendChild(style);

    // 绑定操作按钮事件
    backdrop.querySelectorAll(".replace-btn").forEach((btn) => {
      btn.addEventListener("click", (e: any) => {
        const id = e.currentTarget.getAttribute("data-id");
        handleLogin(id);
      });
    });
  }

  const handleLogoutRemoveToken = async () => {
    const storage = await chrome.storage.sync.get(["baoyiplus_accessToken"]);
    const { baoyiplus_accessToken = "" } = storage;
    const apiurl = `${API_URL}/api/user/logout`;
    return fetch(apiurl, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        Authorization: "Bearer " + baoyiplus_accessToken,
      },
    });
  };
  const handleGetActivity = async () => {
    const storage = await chrome.storage.sync.get(["baoyiplus_accessToken"]);
    const { baoyiplus_accessToken = "" } = storage;
    const apiurl = `${API_URL}/api/user/commonLogin/getActivity`;
    return fetch(apiurl, {
      method: "GET",
      headers: {
        "Content-Type": "application/json",
        Authorization: "Bearer " + baoyiplus_accessToken,
      },
    }).then((result) => {
      result.json().then(async (data) => {
        if (Number(data.code) === 401) {
          await clearLoginData();
          location.reload();
        }
      });
    });
  };
  const polling = new PollingManager(60 * 1000 * 10, handleGetActivity);

  settingsForm.addEventListener("submit", async function (e) {
    e.preventDefault();
    await handleLogin();
  });

  // 检查登录状态函数
  async function checkLoginStatus() {
    const storage = await chrome.storage.sync.get([
      "baoyiplus_accessToken",
      "baoyiplus_expiresIn",
      "baoyiplus_username",
    ]);
    // 解构赋值，设置默认值防止undefined
    const {
      baoyiplus_accessToken = "",
      baoyiplus_expiresIn = 0,
      baoyiplus_username = "",
    } = storage;

    if (baoyiplus_accessToken) {
      const isExpired = checkTokenExpired(baoyiplus_expiresIn);
      if (!isExpired) {
        saveSettings.innerHTML = "登录成功";
        saveSettings.disabled = true;
        // 用户名输入框设置
        openKey.disabled = true;
        openKey.value = baoyiplus_username || "已登录用户";

        openKey.style.backgroundColor = "#f0f0f0"; // 视觉区分

        // 密码框设置
        passwd.disabled = true;
        passwd.value = "********"; // 掩码显示
        passwd.style.backgroundColor = "#f0f0f0";
        polling.start(); // 启动轮询
        // 可选：添加"退出登录"按钮
        if (!document.getElementById("logoutBtn")) {
          const logoutBtn = document.createElement("button");
          logoutBtn.id = "logoutBtn";
          logoutBtn.textContent = "退出登录";
          logoutBtn.style.marginLeft = "10px";
          logoutBtn.setAttribute("type", "button");
          logoutBtn.onclick = async () => {
            await handleLogoutRemoveToken();
            await clearLoginData();
            polling.stop(); // 停止轮询
            location.reload(); // 刷新页面恢复登录表单
          };
          settingsForm.appendChild(logoutBtn);
        }
      } else {
        await clearLoginData();
        saveSettings.innerHTML = "登录已过期，请重新登录";
      }
    }
  }

  // 检查token是否过期（针对时间戳格式）
  function checkTokenExpired(expiresIn: string | number): boolean {
    if (!expiresIn) return true;

    // 统一转换为数字
    const expiryTime =
      typeof expiresIn === "string" ? parseInt(expiresIn) : expiresIn;

    // 获取当前时间戳（毫秒）
    const currentTime = new Date().getTime();
    return currentTime > expiryTime;
  }

  // 清除登录数据
  async function clearLoginData() {
    await chrome.storage.sync.remove([
      "baoyiplus_accessToken",
      "baoyiplus_expiresIn",
    ]);
  }

  // 处理登录逻辑
  async function handleLogin(logOutId = "") {
    saveSettings.disabled = true;
    saveSettings.innerHTML = "登录中...";

    try {
      const result = await login(openKey, passwd, logOutId);

      if (result?.code === 0 && result.data) {
        await chrome.storage.sync.set({
          baoyiplus_accessToken: result.data.accessToken,
          baoyiplus_expiresIn: result.data.expiresIn, // 存储原始时间戳
          baoyiplus_username: openKey.value,
        });
        showLoginSuccess();
      } else if (Number(result?.code) === 409) {
        const data: any = [];
        Object.keys(result.paramMap).forEach((key) => {
          data.push(result.paramMap[key]);
        });
        openIPListDialog(data);
      } else {
        showLoginError(result?.msg || "登录失败");
      }
    } catch (error) {
      console.error("登录异常:", error);
      showLoginError("网络异常");
    }
  }

  // 显示登录成功状态
  function showLoginSuccess() {
    saveSettings.innerHTML = "登录成功";
    saveSettings.disabled = true;
    location.reload();
  }

  // 显示登录错误状态
  function showLoginError(message: string) {
    saveSettings.innerHTML = message;
    saveSettings.style.color = "red";
    saveSettings.disabled = false;

    setTimeout(() => {
      saveSettings.innerHTML = "点击登录";
      saveSettings.style.color = "";
    }, 2000);
  }

  // 登录API
  async function login(
    user: HTMLInputElement,
    passwd: HTMLInputElement,
    logOutId: string = ""
  ) {
    const apiurl = `${API_URL}/api/user/login`;
    const params: any = {
      username: user.value,
      password: passwd.value,
      loginEntrance: "GOODS_COLLECT_PLUGIN",
    };
    if (logOutId) {
      params.logOutId = logOutId;
      params.forceLogin = true;
    }
    const response = await fetch(apiurl, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(params),
    });
    return response.json();
  }
});
